﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf2.Models;
using Wpf2.ViewModels;
using WPFServices;

namespace Wpf2.Views
{
    /// <summary>
    /// Interaction logic for formEditImportOrder.xaml
    /// </summary>
    public partial class FormEditImportOrder
    {
        bool _canExcuteTextChangedEvent = true;
        editImportOrderViewModel editOrderViewModel;

        public FormEditImportOrder(int orderID)
        {
            try
            {
                InitializeComponent();
                editOrderViewModel = new editImportOrderViewModel(orderID);
                OverrideEventOfDataGird();
                DataContext = editOrderViewModel;
                if(!editOrderViewModel.IsMarcle)
                    hideColumnOfMarcle();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        /// <summary>
        /// Ẩn 3 cột liên quan đế Đá Hoa Cương
        /// </summary>
        private void hideColumnOfMarcle()
        {
            dtgInventory.Columns[3].Visibility = System.Windows.Visibility.Hidden;
            dtgInventory.Columns[4].Visibility = System.Windows.Visibility.Hidden;
            dtgInventory.Columns[6].Visibility = System.Windows.Visibility.Hidden;
        }
        private void OverrideEventOfDataGird()
        {
            //dtgInventory.RowEditEnding += dtgInventory_RowEditEnding;
            dtgInventory.LoadingRow += DtgInventoryLoadingRow;
        }

        private static void DtgInventoryLoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        private void ComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                _canExcuteTextChangedEvent = false; // when get content's Commbobox to set text's textbox => TextChanged will be excuted => stop event
                var cmbListToChoose = sender as ComboBox;
                if (cmbListToChoose != null)
                {
                    var stp = cmbListToChoose.Parent as Grid;
                    if (stp != null)
                    {
                        var txtProductName = stp.Children[0] as TextBox;
                        var cbItem = (ComboBoxItem)cmbListToChoose.SelectedItem;
                        if (txtProductName != null)
                        {
                            var p = txtProductName.DataContext as Products;

                            var np = WPFServices.Services.Products.GetProduct(int.Parse(cbItem.Tag.ToString()));

                            if (null != cmbListToChoose.SelectedItem)
                            {
                                if (p != null)
                                {
                                    p.ProductIdAuto = np.ID_PRO_AUTO;
                                    p.ProductName = np.NAME_PRO;
                                    p.ProductId = np.ID_PRO;
                                    p.ProductDescription = np.DESCRIPTIONS;
                                    if (np.DETAILS_PRODUCTS.COST_PRICES != null)
                                        p.CostPrice = (decimal)np.DETAILS_PRODUCTS.COST_PRICES;
                                    p.Unit = new Unit { UnitID = np.DETAILS_PRODUCTS.UNIT.ID_UNIT, UnitName = np.DETAILS_PRODUCTS.UNIT.NAME_UNIT, UnitNote = np.DETAILS_PRODUCTS.UNIT.NOTES_UNIT };
                                    p.catalog = new Catalogs { CatalogName = np.CATALOG.NAME_CATALOG, CatalogNotes = np.CATALOG.NOTES_CATALOG, IDCatalog = np.CATALOG.ID_CATALOG };
                                    p.IsMarble = editOrderViewModel.IsMarcle;// phải thêm để xác định sản phẩm mới là Đá Hoa Cương hay k? (11/5)
                                }
                            }
                        }
                    }
                }
                _canExcuteTextChangedEvent = true;
                editOrderViewModel.addNewProduct();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);

            }
        }

        private void TxtProductNameTextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (!_canExcuteTextChangedEvent || !IsLoaded) // specify is event can run or not
                    return;
                var txtProductName = sender as TextBox;
                if (txtProductName != null)
                {
                    var p = txtProductName.DataContext as Products;
                    if (p != null && !string.IsNullOrEmpty(p.ProductName)) // if text's textbox change when exist Product was binded => delete Product and create new Product to find
                    {
                        var index = editOrderViewModel.ListProducts.IndexOf(p);
                        editOrderViewModel.ListProducts.RemoveAt(index);
                        editOrderViewModel.ListProducts.Insert(index, new Products());
                        return;
                    }
                }
                if (txtProductName == null) return;
                var stp = txtProductName.Parent as Grid;
                if (stp == null) return;
                var cmbListToChoose = stp.Children[1] as ComboBox;
                if (cmbListToChoose == null) return;
                cmbListToChoose.Items.Clear();

                LoadComboboxItem(txtProductName.Text, cmbListToChoose);

                cmbListToChoose.IsDropDownOpen = cmbListToChoose.HasItems;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void TxtProductNameLostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                var txtProductName = sender as TextBox;
                if (txtProductName == null) return;
                var stp = txtProductName.Parent as Grid;
                if (stp == null) return;
                var cmbListToChoose = stp.Children[1] as ComboBox;
                if (cmbListToChoose != null) cmbListToChoose.IsDropDownOpen = false;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message); throw;
            }
        }

        private void LoadComboboxItem(string searchString, ComboBox comboboxResult)
        {
            try
            {
                foreach (var item in editOrderViewModel.ObsProducts)
                    if (!string.IsNullOrEmpty(searchString))
                    {
                        if (isExistInProductList(editOrderViewModel.ListProducts, item))
                            continue;
                        if (item.ProductId.StartsWith(searchString, StringComparison.CurrentCultureIgnoreCase))
                        {
                            var cbItem = new ComboBoxItem {Content = item.ProductId, Tag = item.ProductIdAuto};
                            comboboxResult.Items.Add(cbItem);
                        }
                    }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private bool isExistInProductList(IEnumerable<Products> productList, Products product)
        {
            return productList.Any(item => item.ProductId == product.ProductId);
        }

        // just accept numberic is input into textbox
        private void TxtInventoryCountPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            try
            {
                var textBox = sender as TextBox;
                if (textBox != null)
                {
                    var pro = textBox.DataContext as Products;
                    if (pro != null && pro.ProductIdAuto > 0)
                    {
                        editOrderViewModel.IsChanged = true;
                        editOrderViewModel.IsSaved = false;
                    }
                }
                if (!char.IsDigit(e.Text, e.Text.Length - 1))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

    /*    private void CreateNewOrderDetail(int iOrderID, int iProductIdAuto, int iInventoryCount)
        {
            try
            {
                ORDER_DETAILS newOrderDetail = new ORDER_DETAILS()
        {
            ID_ORD = iOrderID,
            ID_PRO_AUTO = iProductIdAuto,
            QUANTITY = iInventoryCount
        };
                WPFServices.Services.OrderDetails.CreateOrderDetail(newOrderDetail);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private int createNewOrder()
        {
            try
            {
                ORDER newOrder = new ORDER()
        {
            ID_CUS = 7,// mặc định để xác định là trường hợp nhập kho, cần thêm chức năng kiểm tra => tạo nếu không có
            ID_USER = 1,// phai lay user hien tai
            ID_CATALOG = 1, //khong biet lay cai nao??
            ORDER_TYPE = 0,// khong hieu la cai j
            DATE_ORD = DateTime.Now,
            OLD_DEBTS = 0,
            PRE_PAID = 0,
            TOTAL = 0,
            STATUS_ORD = "0"
        };
                return WPFServices.Services.Orders.CreateOrder(newOrder);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
                return 0;
            }
        }*/

        private void TxtProductNameKeydown(object sender, KeyEventArgs e)
        {
            try
            {
                var txt = sender as TextBox;
                if (txt == null) return;
                var p = txt.DataContext as Products;
                if (e.Key != Key.Enter) return;
                PRODUCT np = WPFServices.Services.Products.GetProductByID(txt.Text);
                if (np == null) return;
                if (p != null)
                {
                    p.ProductIdAuto = np.ID_PRO_AUTO;
                    p.ProductName = np.NAME_PRO;
                    p.ProductId = np.ID_PRO;
                    p.ProductDescription = np.DESCRIPTIONS;
                    if (np.DETAILS_PRODUCTS.COST_PRICES != null) p.CostPrice = (decimal)np.DETAILS_PRODUCTS.COST_PRICES;
                    p.Unit = new Unit { UnitID = np.DETAILS_PRODUCTS.UNIT.ID_UNIT, UnitName = np.DETAILS_PRODUCTS.UNIT.NAME_UNIT, UnitNote = np.DETAILS_PRODUCTS.UNIT.NOTES_UNIT };
                    p.catalog = new Catalogs { CatalogName = np.CATALOG.NAME_CATALOG, CatalogNotes = np.CATALOG.NOTES_CATALOG, IDCatalog = np.CATALOG.ID_CATALOG };
                    
                }
                editOrderViewModel.addNewProduct();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

        }

        private void TxtInventoryTextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                editOrderViewModel.caculationPaymentForAllProduct();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void txtDaiRong_textChanged(object sender, TextChangedEventArgs e)
        {
            if (!IsLoaded)
                return;
            try
            {
                var textBox = sender as TextBox;
                if (textBox != null)
                {
                    var pro = textBox.DataContext as Products;
                    if (pro != null && pro.ProductIdAuto > 0)
                    {
                        editOrderViewModel.IsChanged = true;
                        editOrderViewModel.IsSaved = false;
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void CaculationPayment(object sender, RoutedEventArgs e)
        {
            editOrderViewModel.caculationPaymentForAllProduct();
        }

    }
}
